﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BaseController.cs" company="DTTB">
//   2011
// </copyright>
// <summary>
//   Defines the BaseController type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using DTTB.MV2.QUANLYNHANSUTIENLUONG.BussinessDelegate.HistoryDelegate;

namespace DTTB.MV2.QUANLYNHANSUTIENLUONG.Controllers.Base
{
    /// <summary>
    /// The base controller.
    /// </summary>
    public class BaseController : Controller
    {
        HistoryDelegate HistoryDelegate = new HistoryDelegate();
        //protected 

        /// <summary>
        /// Gets or sets a value indicating whether this instance is check authorization.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is check authorization; otherwise, <c>false</c>.
        /// </value>
        public bool IsCheckAuthorization { get; set; }

        /// <summary>
        /// Method called before the action method is invoked.
        /// </summary>
        /// <param name="filterContext">Contains information about the current request and action.</param>
        /// <exception cref="System.NotImplementedException">Thrown when </exception>
        /// <exception cref="System.ArgumentNullException">Thrown when </exception>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //// If session exists
            if (filterContext.HttpContext.Session != null)
            {
                ////if new session
                if (filterContext.HttpContext.Session.IsNewSession)
                {
                    string cookie = filterContext.HttpContext.Request.Headers["Cookie"];

                    //// if cookie exists and sessionid index is greater than zero

                    if ((cookie != null) && (cookie.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        ////redirect to desired session 
                        ////expiration action and controller
                        filterContext.Result = RedirectToAction("Login", "Authentication");
                        return;
                    }
                }
            }

            base.OnActionExecuting(filterContext);
        }

        //Ghi nhận lại thông tin user thao tác khi sử dụng hệ thống
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var module = filterContext.RouteData.GetRequiredString("controller");
            var action = filterContext.RouteData.GetRequiredString("action");
            try
            {
                if(!Request.IsAjaxRequest())
                {
                    HistoryDelegate.SaveToHistory(module, action, Request.Url != null ? Request.Url.ToString() : string.Empty);    
                }
            }   
            catch (Exception)
            {
                HistoryDelegate.SaveToHistory(module, action, Request.Path ?? string.Empty);    
            }

        }
     
        /// Initializes data that might not be available when the constructor is called.
        /// 
        /// <param name="requestContext">The HTTP context and route data.</param>
        protected override void Initialize(RequestContext requestContext)
        {
            var controllerName = requestContext.RouteData.GetRequiredString("controller");
            var actionName = requestContext.RouteData.GetRequiredString("action");
            var accessingResource = controllerName + "_" + actionName;

            string isDevelopmentMode = ConfigurationManager.AppSettings["IsDevelopmentMode"];
            IsCheckAuthorization = ConfigurationManager.AppSettings["IsCheckAuthorization"].Equals("true")
                                       ? true
                                       : false;

            if (!String.IsNullOrEmpty(isDevelopmentMode) && isDevelopmentMode.Equals("false"))
            {
                if (this.IsCheckAuthorization)
                {
                    if (System.Web.HttpContext.Current.Session["USERNAME"] == null || string.IsNullOrEmpty(System.Web.HttpContext.Current.Session["USERNAME"].ToString()) || Convert.ToInt32(System.Web.HttpContext.Current.Session["USERID"]) == 0)
                    {
                        if (requestContext.HttpContext.Request.IsAjaxRequest())
                        {
                            requestContext.HttpContext.Response.StatusCode = 401;
                            requestContext.HttpContext.Response.End();
                        }
                        else
                            requestContext.HttpContext.Response.Redirect("~/Authentication/Login");
                        base.Initialize(requestContext);
                    }

                    // by default assign home page as landing page for all user
                    //if (!(controllerName.Equals("QuanLyHoChieu") && actionName.Equals("DsHoChieus")) && !SessionDetail.USERNAME.Equals("admin"))
                    //if (!(controllerName.Equals("QuanLyHoChieu") && actionName.Equals("DsHoChieus")) && !SessionDetail.ISADMIN)
                    if (!(controllerName.Equals("Home") && actionName.Equals("Index")) && !Convert.ToBoolean(System.Web.HttpContext.Current.Session["ISADMIN"]))
                    {
                        var isAuthorized = false;
                        var permissionList = (List<string>)(System.Web.HttpContext.Current.Session["PermissionList"]);

                        if (permissionList != null)
                        {
                            if (permissionList.Any(permission => accessingResource.ToLower().Trim().Equals(permission.ToLower().Trim())))
                            {
                                isAuthorized = true;
                            }
                        }
                        if (Convert.ToBoolean(System.Web.HttpContext.Current.Session["ISADMIN"]))
                        {
                            isAuthorized = true;
                        }

                        if (!isAuthorized)
                        {
                            requestContext.HttpContext.Response.Redirect("~/Authentication/NoAccessPermission");
                        }
                        else
                        {
                            base.Initialize(requestContext);
                        }
                    }
                    else
                    {
                        base.Initialize(requestContext);
                    }
                }
                else
                {
                    base.Initialize(requestContext);
                }
            }
            else
            {
                base.Initialize(requestContext);
            }
        }


        //protected override void OnException(ExceptionContext ExceptionContext)
        //{
        //    ExceptionContext.Result = RedirectToAction("~/Authentication/Error");
        //}


        ///// <summary>
        ///// Called after the action method is invoked.
        ///// </summary>
        ///// <param name="filterContext">Information about the current request and action.</param>
        //protected override void OnActionExecuted(ActionExecutedContext filterContext)
        //{
            
        //}
    }
}